<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-10-11
 * Time: 10:27
 */

namespace App\Http\Controllers\Api\V1\Front\Wx;


use App\Http\Controllers\Controller;
use App\Libs\httpUtil;
use App\Libs\OSS;
use App\Models\AdditionalFields;
use App\Models\User;
use App\Models\UserAddition;
use App\Libs\wxBizDataCrypt;
use App\Services\Wx\WxService;
use Illuminate\Http\Request;

class WxController extends Controller
{
    /**
     * 通过code获取用户详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfoByCode(Request $request)
    {
        $code = $request->code;
        if (!$code) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . env("APPID") . "&secret=" . env("APPKEY") . "&code=" . $code . "&grant_type=authorization_code";
        $http = new httpUtil();
        $accessToken = $http->http_get($url);
        if (!$accessToken) {
            return $this->apiResponse('', config('errorCode.INVALID_CODE_PARAMS'));
        }
        $result = json_decode($accessToken, true);

        if (!empty($result['errcode'])) {
            \Log::error(' WxController getUserInfoByCode  code ' . $accessToken);
            return $this->apiResponse('', config('errorCode.INVALID_CODE_PARAMS'));
        }
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $result['access_token'] . "&openid=" . $result['openid'] . "&lang=zh_CN";
        $userInfo = $http->http_get($url);
        if (!$userInfo) {
            return $this->apiResponse('', config('errorCode.INVALID_CODE_PARAMS'));
        }
        $result = json_decode($userInfo, true);

        if (!empty($result['errcode'])) {
            \Log::error('WxController getUserInfoByCode  get user info' . $userInfo);
            return $this->apiResponse('', config('errorCode.INVALID_CODE_PARAMS'));
        }

        //查看用户是否已经注册
        $user = User::where('openId', $result['openid'])->first();
        if ($user) {
            if(!$user['userStatus']){
                return $this->apiResponse('', config('errorCode.PROHIBIT_USER'));
            }
            User::where('openId', $result['openid'])->update(['openId' => $result['openid'], 'nickName' => $result['nickname'], 'avatar' => $result['headimgurl']]);
            $result['flag'] = 1;
            $result['userId'] = $user['userId'];
        } else {
            $user['openId'] = $result['openid'];
            $user['nickName'] = $result['nickname'];
            $user['avatar'] = $result['headimgurl'];
            $user['accessToken'] = encrypt($result['openid'] . time());
            $userId = User::insertGetId($user);
            $result['userId'] = $userId;
            $result['flag'] = 1;
        }
        $user = User::where(['userId' => $result['userId']])->first();
        $userAddition = UserAddition::select('t1.fieldsId', 't1.value', 't2.value as key', 't1.useradditionId')
            ->from((new UserAddition())->getTable() . ' as t1')
            ->join((new AdditionalFields())->getTable() . ' as t2', 't1.fieldsId', '=', 't2.id')
            ->where('userId', $result['userId'])->get();
        $user['userAddition'] = $userAddition;
        if ($user['scanFlag']) {
            $user['leadingInStatus'] = "WORK";
        } else {
            $user['leadingInStatus'] = "USER";
        }
        $user['registerStatus'] = 1;
        return $this->apiResponse($user);
        /* if($user){
             $user['registerStatus'] = 1;
             if($user['userStatus'] === 0){
                 return $this->apiResponse('', config('errorCode.USER_NO_USER'));
             }
             if($user['scanFlag']){
                 $user['leadingInStatus'] = "WORK";
             }else{
                 $user['leadingInStatus'] = "USER";
             }
             return $this->apiResponse($user);
         }
         $result['registerStatus'] = 0 ;*/
        // return $this->apiResponse($result);

    }

    /**
     *  微信JS权限配置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getWxConfig(Request $request)
    {

        $server = new WxService();

        $url = $request->url;
        if (!$url) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $ticket = $server->getJsapiTicket();
        $noncestr = noncestr(8);
        $timestamp = time();
        $signRaw = "jsapi_ticket=$ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $sign = sha1($signRaw);
        $result['appId'] = env("APPID");
        $result['nonceStr'] = $noncestr;
        $result['timestamp'] = $timestamp;
        $result['signature'] = $sign;
        return $this->apiResponse($result);
    }

    /**
     * 微信小程序登录
     */

    public function login(Request $request) {
        $code = $request->code;
        if(!$code){
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        //接口地址
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".env("APPID")."&secret=".env("AppSecret")."&js_code=".$code."&grant_type=authorization_code";
        $http = new httpUtil();
        $data = $http->http_get($url);
        //return $data;
        if(!$data){
            return $this->apiResponse('', config('errorCode.INVALID_CODE_PARAMS'));
        }
        $result = json_decode($data, true);
        if(!array_key_exists('openid',$result)) {
            return $this->apiResponse('', config('errorCode.SERVER_EXCEPTION'));
        }
        $session_key = $result['session_key'];
        cache(['session_key'.$result['openid'] => $session_key], 3);
        $user = Wxinfo::where('openId',$result['openid'])->first();
        if (!$user) {
            $data = [];
            $data['openId'] = $result['openid'];
            $data['session_key'] = 'session_key'.$data['openId'];
            return $this->apiResponse($data);
        }
        return $this->apiResponse($user);
    }

    /**
     * 微信小程序注册
     */

    public function register(Request $request)
    {
        $openid = $request->openId;
        $sessionKey = cache('session_key' . $openid);

        $appid = env("APPID");
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $iv = $request->iv;

        $encryptedData = $request->encryptedData;
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {

            //print($data . "\n");
            $result = json_decode($data, true);
            $openid = $result['openId'];
            $user = Wxinfo::where('openId', $openid)->first();
            if (!$user) {
                $res = [];
                $res['openid'] = $openid;
                $res['avatar'] = $result['avatarUrl'];
                $res['nickName'] = $result['nickName'];
                $res['UserType'] = 'NOTSELECT';
                $res['createTime'] = date('y-m-d h:i:s', time());
                $status = Wxinfo::create($res);
                if ($status) {
                    $users = Wxinfo::where('openId', $res['openid'])->first(['avatar', 'UserType', 'nickName']);
                    return $this->apiResponse($users);
                }
            }
            return $this->apiResponse($user);

        } else {
            return $this->apiResponse($errCode);
        }

    }

    /**
     * 推送消息
     */
    public function PushMessage(Request $request)
    {
        $openid = $request->openid;
        $token = new WxService();
        $access_token = $token->getAccessToken();
        $push_url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $access_token;
        $parmArr = [
            //touser template_id page form_id data color
            "touser" => $openid,
            "template_id" => "kVd63lsQ5XXrm_bmi5D1bxujY1VNCmtNNAOehbmyP5A",
            "page" => '', //跳转页面所用
            'form_id' => '',  //form-id
            "data" => [
                "keyword1" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                "keyword2" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                "keyword3" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                "keyword4" => [
                    "value" => '',
                    "color" => "#173177"
                ],
            ]
        ];

        $paramObj = json_encode($parmArr);
        $res = [];
        $http = new httpUtil();
        $status = $http->http_post($push_url, $paramObj);
        $status = json_decode($status,true);
    }
}